function cartInit(d){
    //dom
    var box = $('.ptbasket');
    var shopTpl = $('.basket-goods').remove()
    var goodsTpl = shopTpl.find('.goods-category').remove()
    var label = goodsTpl.find('.js-label').remove()
    var bar = $('.basket-bar')
    //数据
    var total = d.data.total;
    var list = d.data.list;
    //结构
    var shopIds = [];


    for(var i=0;i<total;i++){
        var item = list[i];
        var shopId = item.shop_id;
        //新建商店
        if(shopIds.indexOf(shopId) == -1){
            shopIds.push(shopId);
            console.log(shopIds)
            var thisShop = shopTpl.clone();
            if(box.find('basket-goods').length<1){
                bar.after(thisShop);
            }
            //填入数据
            thisShop.attr('shopId', shopId);
            thisShop.find('.js-seller-name').text(item.shop.company)
            //var newGood = 
        }else{
            thisShop = box.find("[shopId="+shopId+"]")
        }

        //填入商品
        (function(){
            var thisGood = goodsTpl.clone().appendTo(thisShop.find('.basket-goods-plate'))

            thisGood.attr('id', item.cart.cart_id);
            thisGood.find('.js-good-check').val(item.cart.cart_id).attr('name','cartIds['+item.shop_id+'][]');
            thisGood.find('.js-img').attr('src', item.thumb)
            thisGood.find('.js-name').text(item.name);
            thisGood.find('.js-good-link').attr('href',_root+"../goods/index?id="+item.id);
            thisGood.find('.js-amount').val(item.cart.number);
            var labelBox = thisGood.find('.goods-label')
            for(var i=0;i<item.label.length;i++){
                var labelData = item.label[i]
                if(labelData['show_in_detail']==0) continue;
                var oneLabel = label.clone()
                oneLabel.text(labelData.name).attr('labelId', labelData.id);
                var name = labelData.name
                switch(name){
                    case '热卖':
                        oneLabel.addClass('hot-sell');
                        break;
                    case '正品':
                        oneLabel.addClass('quality-goods');
                        break;
                    case '闪发':
                        oneLabel.addClass('speed-delivery')
                        break;
                }
                labelBox.append(oneLabel)
            }
            var defaultAttr = item.cart.attr_id;
            var attrBox = thisGood.find('.js-size-box')
            var attrTpl = attrBox.find('option').remove()
            for(var i=0;i<item.attr.length;i++){
                var attrData = item.attr[i]
                var oneAttr = attrTpl.clone()
                oneAttr.text(attrData.name)
                .val(attrData.id)
                .attr('stock',attrData.stock);
                attrBox.append(oneAttr)

                if(attrData.id==defaultAttr){
                    oneAttr.prop('selected', true)
                }
            }
            thisGood.find('.js-unit-price').text('￥'+item.price.base_price);
            thisGood.find('.js-order-money').text('￥'+item.price.base_price*item.cart.number).attr('perPrice', item.price.base_price).attr('total', item.price.base_price*item.cart.number);
            
        })()
        
    }
}

function calMoney(){
    var total = 0;
    $('.js-order-money').each(function(index, el) {
        if($(this).closest('.goods-category').find('.js-good-check').is(':checked')){
            total += parseFloat($(this).attr('total'));
        }
    });
    $('.js-order-total-price').text(total.toFixed(2))
}

function checkStock(amount,goodTpl,noAlert){
    console.log(amount)
    console.log(goodTpl)
    var stock = parseInt(goodTpl.find(".js-type:selected").attr('stock'),10);
    var finalValue = amount;

    var result = true;

    //无货
    if(stock<1){
        if(!noAlert) alert('此规格暂时无货')
        goodTpl.find('.js-good-check').attr('checked', false).prop('checked', false)
        finalValue = 0;
        result = false;
    }else if(amount<1){
        finalValue = 1;
        result = false;
    }else if(amount>stock){
        alert('超出库存');
        finalValue = stock; 
        result = false;
    }
    goodTpl.find('.js-amount').val(finalValue)
    var thisTotal = parseFloat(parseFloat(goodTpl.find('.js-order-money').attr('perPrice')).toFixed(2)*finalValue).toFixed(2)
    goodTpl.find('.js-order-money').text('￥'+thisTotal).attr('total', thisTotal);
    calMoney()

    return result;
}

function modify(goodTpl){
    var cart_id = goodTpl.attr('id')
    var attr_id = goodTpl.find('.js-size-box').val();
    var number  = goodTpl.find('.js-amount').val();
    api.solo('cartUpdate',[cart_id,attr_id,number],function(d){
        if(d.state!=200){
            //alert(d.message)
            return;
        }
    })
}


$(document).ready(function($) {
    //购物车初始化
    api.solo('cartList',[],function(d){
        if(d.state!=200){
            alert('购物车数据请求超时，请重试')
            return false;
        }
        //初始化购物车
        cartInit(d)
        //初始化全部选择
        $("input[type='checkbox']").prop('checked', true)
        calMoney()
        //全选
        $('.js-check-all').click(function(){
            if($(this).is(':checked')){
                $("input[type='checkbox']").prop('checked', true)   
            }else{
                $("input[type='checkbox']").prop('checked', false)
            }
            calMoney()
        })
        //检查所有产品
        $(".goods-category").each(function(index, el) {
            checkStock($(this).find('.js-amount').val(),$(this),1)
        });
        //商家选框
        $('.js-seller-check').click(function(){
            var goodsCheck = $(this).closest('.basket-goods').find('.js-good-check')
            if($(this).is(':checked')){
                goodsCheck.prop('checked', true)    
            }else{
                goodsCheck.prop('checked', false)
            }
            calMoney()
        })
        //商品选框
        $('.js-good-check').click(function(){
            //TODO
            calMoney()
        })
        //选数量
        $(".js-amount").bind("input propertyChange",function () {
            var goodTpl = $(this).closest('.goods-category')
            modify(goodTpl)
            checkStock($(this).val(),goodTpl)
        })
        $('.js-amount-control').click(function(e){
            e.preventDefault()
            var goodTpl = $(this).closest('.goods-category')
            var amountInput = $(this).closest('.order-amount').find('.js-amount');
            var value = amountInput.val()
            if($(this).hasClass('minus')){
                value--
            }else{
                value++
            }
            checkStock(value,goodTpl)
            modify(goodTpl)
        })

        //改变类型
        $('.js-size-box').change(function(){
            var goodTpl = $(this).closest('.goods-category')
            modify(goodTpl)
            checkStock(goodTpl.find('.js-amount').val(),goodTpl)
        })
        
        //删除
        $('.js-remove').click(function(e) {
            e.preventDefault();
            var thisGood = $(this).closest('.goods-category')
            var id = thisGood.attr('id');
            console.log(id)
            api.solo('cartRemove',[id],function(d){
                if(d.state==200){
                    thisGood.remove()
                    calMoney()
                    //userbar
                    $('.control-cart-num').html(parseInt($('.control-cart-num').html(),10)-1)
                }else{
                    alert('删除失败')
                }
            })
        });

        //提交
        $('#confirmCart').click(function(event) {
            event.preventDefault();
            var allEmpty = 1;
            var nostock = 0;

            $(".js-good-check").each(function(index, el) {
                if($(this).is(':checked')){
                    allEmpty = 0;
                    //return false;
                    var tpl = $(this).closest('.goods-category')
                    if(!checkStock( tpl.find('.js-amount').val(), tpl)) {
                        nostock = 1;
                        return false;
                    }
                }
            });
            if(allEmpty==1){
                alert('请选择您要购买的产品')
                return false;
            }else if(nostock==1){
                return false;
            }else{ 
                $('form').submit();
            }
        });
        
    })
});


    
